package com.gistone.commis.api.restController;

import com.gistone.commis.dto.EditorResult;
import com.gistone.commis.dto.FieldError;
import com.gistone.commis.entity.Community;
import com.gistone.commis.entity.Depart;
import com.gistone.commis.entity.Fund;
import com.gistone.commis.entity.PositionType;
import com.gistone.commis.mapper.CommunityMapper;
import com.gistone.commis.mapper.PositionTypeMapper;
import com.gistone.commis.util.DataTablePageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangfan on 2017/5/5.
 */
@RestController("apiPositionTypeController")
@RequestMapping("api/positionType")
public class PositionTypeController {

    private static final Logger logger = LoggerFactory.getLogger(PositionTypeController.class);


    @Autowired
    private PositionTypeMapper positionTypeMapper;




    /**
     * 获取所有社区
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/all")
    public List<PositionType> loadAll() {
        return positionTypeMapper.findPositionTypes();
    }


    /**
     * 新建y用户信息
     *
     * @param request
     * @param response
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = "/create")
    public EditorResult<PositionType> create(HttpServletRequest request, HttpServletResponse response) {


        PositionType positionType = new PositionType();
        EditorResult<PositionType> positionTypeEditorResult = new EditorResult<>();
        List<FieldError> fieldErrorList = new ArrayList<>();
//        house.setHouseId(houseId);
        getPositionType (request, "data[0][", positionType,fieldErrorList);


        if(fieldErrorList.size()>0){
            logger.error("字段格式错误");
            positionTypeEditorResult.setFieldErrors(fieldErrorList);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return positionTypeEditorResult;
        }
        if (positionTypeMapper.insertSelective(positionType)> 0) {
            List<PositionType> data = new ArrayList<>();
            data.add(positionTypeMapper.selectByPrimaryKey(positionType.getPositionId()))	;
            positionTypeEditorResult.setData(data);
        } else {
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }


        return positionTypeEditorResult;
    }

    /**
     * 批量修改房屋信息， id以,号分割
     *
     * @param houseIdStr
     * @param request
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.PUT, value = "/edit")
    public Object edit(@RequestParam("id") String houseIdStr, HttpServletRequest request, HttpServletResponse response) {
        String[] arr = houseIdStr.split(",");
        EditorResult<PositionType> positionTypeEditorResult = new EditorResult<>();

        List<PositionType> data =new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            int positionTypeId = Integer.valueOf(arr[i]);

            System.out.println(positionTypeId);
            PositionType positionType = new PositionType();

            positionType.setPositionId(positionTypeId);
            List<FieldError> fieldErrorList = new ArrayList<>();
            getPositionType(request, "data[" + positionTypeId + "][", positionType , fieldErrorList );
            if(fieldErrorList.size()>0){
                logger.error("字段错误");
                positionTypeEditorResult.setFieldErrors(fieldErrorList);
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return positionTypeEditorResult;
            }
            if (positionTypeMapper.updateByPrimaryKeySelective(positionType) > 0) {
                data.add(positionTypeMapper.selectByPrimaryKey(positionTypeId));


            }else{
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }


        }

        positionTypeEditorResult.setData(data);
        return positionTypeEditorResult;


    }


    /**
     * 用户删除
     * 通过房屋ID批量删除房屋信息， id以,号分割
     *
     * @param positionTypeIdStr
     * @param request
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.DELETE, value = "/remove")
    public Object remove(@RequestParam("id") String positionTypeIdStr, HttpServletRequest request, HttpServletResponse response) {
        String[] arr = positionTypeIdStr.split(",");
        EditorResult<PositionType> positionTypeEditorResult = new EditorResult<>();
        for (int i = 0; i < arr.length; i++) {
            int positionTypeId = Integer.valueOf(arr[i]);
            if (positionTypeMapper.deleteByPrimaryKey(positionTypeId) > 0) {
                System.out.println("删除" + positionTypeId + "成功！");


            } else {
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }
        }
        return positionTypeEditorResult;


    }

    /**
     * dataTables 表单数据返回
     *
     * @param request
     * @return
     */

    @RequestMapping(method = RequestMethod.GET, value = "/pageDatatables")
    public DataTablePageUtil<PositionType> pageDatatables(HttpServletRequest request, PositionType positionType) {
//		HttpSession httpSession = request.getSession();
//		PositionType positionType = (PositionType) httpSession.getAttribute("positionTypeInfo");
//		logger.info("用户信息：" + positionType.toString());
//		int community_id = positionType.getCommunity().getCommunityId();
//		positionType.setCommunityId(community_id);
        System.out.println(positionType.toString());

//        List<Community> communities =communityMapper.findCommunitys();
//        Options os =new Options();
//        List<Option> optionList =new ArrayList<>();
//        for (Community community : communities) {
//
//            Option option =new Option();
//            option.setLabel(community.getCommunityName());
//            option.setValue(community.getCommunityId());
//            optionList.add(option);
//
//
//        }
//        os.setCommunityId(optionList);
//        List<Depart> departs =departMapper.findDeparts();
//        optionList =new ArrayList<>();
//        for (Depart depart : departs) {
//
//            Option option =new Option();
//            option.setLabel(depart.getDepartName());
//            option.setValue(depart.getDepartId());
//            optionList.add(option);
//
//
//        }
//
//        os.setDepartId(optionList);



        DataTablePageUtil<PositionType> dataTable = new DataTablePageUtil<>(request);

        PageHelper.startPage(dataTable.getPage_num(), dataTable.getPage_size());
        List<PositionType> list = positionTypeMapper.selectSelective(positionType);
        PageInfo<PositionType> pageInfo =new PageInfo<>(list);
        dataTable.setDraw(dataTable.getDraw());
        dataTable.setData(pageInfo.getList());
//        dataTable.setOptions(os);
        dataTable.setRecordsTotal((int)pageInfo.getTotal());
        dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
        //返回数据到页面


        return dataTable;

    }

    private void getPositionType(HttpServletRequest request, String prefix, PositionType positionType,List<FieldError> fieldErrorList ) {



        if(request.getParameter(prefix + "positionName]").isEmpty()){
            logger.error("格式不正确");
            FieldError fieldError =new FieldError("positionName","职位名称不能为空");
            fieldErrorList.add(fieldError);
        }else {
            positionType.setPositionName(request.getParameter(prefix + "positionName]"));
        }

        try {
            positionType.setPositionJwage(Double.valueOf(request.getParameter(prefix + "positionJwage]")));
        } catch (NumberFormatException e) {
            logger.error("数量格式不正确，必须为数字");
            FieldError fieldError =new FieldError("positionJwage","资产类别格式不正确，必须为数字");
            fieldErrorList.add(fieldError);
        }
        try {
            positionType.setPositionGwjt(Double.valueOf(request.getParameter(prefix + "positionGwjt]")));
        } catch (NumberFormatException e) {
            logger.error("数量格式不正确，必须为数字");
            FieldError fieldError =new FieldError("positionGwjt","资产类别格式不正确，必须为数字");
            fieldErrorList.add(fieldError);
        }

        try {
            positionType.setPositionQdnx(Double.valueOf(request.getParameter(prefix + "positionQdnx]")));
        } catch (NumberFormatException e) {
            logger.error("数量格式不正确，必须为数字");
            FieldError fieldError =new FieldError("positionQdnx","资产类别格式不正确，必须为数字");
            fieldErrorList.add(fieldError);
        }





    }



}
